/*
    Author:xfz
    Desc:对调试打印进行一层抽象，方便后续使用操作
*/

#include "ft32f0xx.h"
#include "bsp_print.h"
#include <stdio.h>
void bsp_print_init(void)
{
    // PB6 TX PB7 RX
    USART_InitTypeDef usart_InitTypeDef;
    GPIO_InitTypeDef Gpio_InitStructure;
    // 打开GPIOB外设使能
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
    //打开USART1 外设使能
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
    // PIN 6和PIN 7设为外设功能
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_0); // TX
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_0); // RX
    //初始化GPIO设置
    //初始化PIN6
    Gpio_InitStructure.GPIO_Pin = GPIO_Pin_6;
    Gpio_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    Gpio_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
    Gpio_InitStructure.GPIO_OType = GPIO_OType_PP;
    Gpio_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOB, &Gpio_InitStructure);
    //初始化pin7
    Gpio_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_Init(GPIOB, &Gpio_InitStructure);
    //初始化串口配置
    usart_InitTypeDef.USART_BaudRate = BAUD;
    usart_InitTypeDef.USART_WordLength = USART_WordLength_8b;
    usart_InitTypeDef.USART_StopBits = USART_StopBits_1;
    usart_InitTypeDef.USART_Parity = USART_Parity_No;
    usart_InitTypeDef.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    usart_InitTypeDef.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_Init(USART1, &usart_InitTypeDef);
    USART_Cmd(USART1, ENABLE);
    bsp_print_RxReset();//丢掉缓存
}

/**
 * @brief  Retargets the C library printf function to the USART.
 * @param  None
 * @retval None
 */
int fputc(int ch, FILE *f)
{
    /* Place your implementation of fputc here */
    /* e.g. write a character to the USART */
    USART_SendData(USART1, (uint8_t)ch);

    /* Loop until transmit data register is empty */
    while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
    {
    }

    return ch;
}
int fgetc(FILE *f)
{
    while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET)
    {
    }
    return (int)USART_ReceiveData(USART1);
}
GBool bsp_print_isRxBufNotEmpty(void)
{
    return USART_GetFlagStatus(USART1, USART_FLAG_RXNE);
}
GBool bsp_print_rxBufferTimeout(void)
{
    uint32_t scantimeout = 0;
    fflush(stdin);
    while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET)
    {
        scantimeout++;
        if (scantimeout >= SCANF_TIMEOUT)
        {
            break;
        }
    }
    if (scantimeout < SCANF_TIMEOUT)
    {
        return GFalse;
    }
    else
    {
        return GTrue;
    }
}
void bsp_print_RxReset(void)
{
    uint32_t scantimeout = 0;
    while (GTrue)
    {
        while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET)
        {
            scantimeout++;
            if (scantimeout >= (SCANF_TIMEOUT / 10))
            {
                return;
            }
        }
        USART_ReceiveData(USART1);
    }
}
